<?php

namespace App\Http\Controllers\Home;

use App\Models\ActivityCategorys;
use App\Models\Activitys;
use App\Models\Areas;
use App\Models\Articles;
use App\Models\Categorys;
use App\Models\Demands;
use App\Models\Goods;
use App\Models\GoodsCategorys;
use App\Models\HotSearchs;
use App\Models\Stores;
use App\Models\WordCategorys;
use App\Models\Words;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class SearchController extends Controller
{
    /**
     * 热门搜索
     * @param url home.search.hotSearchApi
     * @return bool
     */
    public function hotSearchApi() {
        try{
            $lists = HotSearchs::where('status','<>',-1)->orderBy("count", "desc")->limit(10)->get(['content','count','type']);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }
    /**
     * 搜索
     * @param url home.search.searchApi
     * @param keyword 搜索词
     * @param cid 分类
     * @param page 页码
     * @param sid 排序
     * @param orderby 排序方式
     * @param key 类型：1供应商 2活动 3商品 4需求 5新闻 6文档
     * @return bool
     */
    public function searchApi(Request $request) {
        try{
            $keyword = (string)$request->post("keyword",'寻找');
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid');//排序
            $orderby = (string)$request->get('orderby','desc');//排序方式
            $key = (int)$request->post("key",4);//类型：1供应商 2活动 3商品 4需求 5新闻 6文档
            $params = [];
            $params['keyword'] = $keyword;
            $params['cid'] = (int)$request->get('cid');
            if($key == 1){
                $params['recommend'] = (int)$request->get('recommend');
                $params['area'] = (int)$request->get('area');
                if ($sid == 1){
                    $sort = 'service';
                }elseif ($sid == 2){
                    $sort = 'view';
                }elseif ($sid == 3){
                    $sort = 'praise';
                }else{
                    $sort = 'created_at';
                }
                $lists = Categorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
                $fields = ['id','store_name','logo','call','view','service','praise','service_scope','hot','quality'];
                //二级分类
                if(empty($params['cid'])){
                    $lists['children'] = Categorys::where('pid','<>','0')->get(['id','name','pid'])->toArray();
                }else{
                    $lists['children'] = Categorys::getcates(['pid'=>$params['cid']],['id','name','pid'])->toArray();
                }
                $lists['store'] = Stores::allLists($params, $fields, $page, 5, $sort, $orderby);
                foreach ($lists['store'] as $key=>$val){
                    $lists['store'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists['store'][$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                    $lists['store'][$key]['praise'] = strlen($val['praise'])>=4 ? '999+' : $val['praise'];
                    $lists['store'][$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                }
                $lists['area'] = Areas::get(['id','name','pid']);//服务区域
            }elseif ($key == 2){
                $params['charge'] = (int)$request->get('charge');
                $params['area'] = (int)$request->get('area');
                $now_time = date('Y-m-d H:i:s');
                $act_state = (int)$request->get('act_state');//活动状态
                if($act_state == 1){
                    $map['enroll_at'] = $now_time;
                }elseif ($act_state == 2){
                    $map['start_at'] = $now_time;
                }
                if ($sid == 1){
                    $sort = 'view';
                }elseif ($sid == 2){
                    $sort = 'start_at';
                }elseif ($sid == 3){
                    $sort = 'number';
                }elseif ($sid == 4){
                    $sort = 'cost';
                }else{
                    $sort = 'created_at';
                }
                $lists = ActivityCategorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
                //二级分类
                if(empty($params['cid'])){
                    $lists['children'] = ActivityCategorys::where('pid','<>','0')->where('status','<>',-1)->get(['id','name','pid'])->toArray();
                }else{
                    $lists['children'] = ActivityCategorys::getcates(['pid'=>$params['cid']],['id','name','pid'])->toArray();
                }
                $lists['act'] = Activitys::allLists($params, $fields=['*'], $page, 5, $sort, $orderby);
                foreach ($lists['act'] as $key=>$val){
                    $lists['act'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists['act'][$key]['limit'] = strlen($val['limit'])>=4 ? '999+' : $val['limit'];
                    if($now_time <= $val['enroll_at']){
                        $lists['act'][$key]['act_state'] = '报名中';
                    }elseif ($now_time >= $val['start_at']){
                        $lists['act'][$key]['act_state'] = '已举办';
                    }
                }
                $lists['area'] = Areas::get(['id','name','pid']);//服务区域
            }elseif ($key == 3){
                $params['type'] = (int)$request->get('type');
                if ($sid == 1){
                    $sort = 'salenum';
                }elseif ($sid == 2){
                    $sort = 'view';
                }elseif ($sid == 3){
                    $sort = 'praise';
                }else{
                    $sort = 'created_at';
                }
                $lists = GoodsCategorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
                //二级分类
                if(empty($params['cid'])){
                    $lists['children'] = GoodsCategorys::where('pid','<>','0')->get(['id','name','pid'])->toArray();
                }else{
                    $lists['children'] = GoodsCategorys::getcates(['pid'=>$params['cid']],['id','name','pid'])->toArray();
                }
                $fields = ['id','title','thumb','price','description','salenum','cate_id','cate_pid'];
                $lists['goods'] = Goods::allLists($params, $fields, $page, 5, $sort, $orderby);
                foreach ($lists['goods'] as $key=>$val){
                    $lists['goods'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                }
            }elseif ($key == 4){
                $params['area'] = (int)$request->get('area');
                $params['bid'] = (int)$request->get('bid');//2投标中 3已完成
                $params['urgent'] = (int)$request->get('urgent');//是否加急 1否 2是
                $end = (string)$request->get('end');//截止时间 1:一天内 2:三天内 3:七天内 4:一个月内 5:一个月以上
                $budget = (string)$request->get('budget');//预算区间 1:0-1万 2:1万-5万 3:5万-10万 4:10万-50万 5:50万-100万 6:100万以上
                //排序
                if ($sid == 1){
                    $sort = 'created_at';
                }elseif ($sid == 2){
                    $sort = 'price';//预算
                }else{
                    $sort = 'created_at';
                }
                //截止时间
                if($end == 1){
                    $params['start_time'] = Carbon::now()->startOfDay()->toDateTimeString();
                    $params['end_time'] = Carbon::now()->endOfDay()->toDateTimeString();
                }elseif ($end == 2){
                    $params['start_time'] = Carbon::now()->startOfDay()->toDateTimeString();
                    $params['end_time'] = Carbon::parse('+3 days')->toDateTimeString();
                }elseif ($end == 3){
                    $params['start_time'] = Carbon::now()->startOfWeek()->toDateTimeString();
                    $params['end_time'] = Carbon::now()->endOfWeek()->toDateTimeString();
                }elseif ($end == 4){
                    $params['start_time'] = Carbon::now()->startOfMonth()->toDateTimeString();
                    $params['end_time'] = Carbon::now()->endOfMonth()->toDateTimeString();
                }elseif ($end == 5){
                    $params['start_time'] = Carbon::now()->endOfMonth()->toDateTimeString();
                }
                //预算区间
                if ($budget == 1){
                    $params['price_two'] = 1;
                }elseif ($budget == 2){
                    $params['price_one'] = 1;
                    $params['price_two'] = 5;
                }elseif ($budget == 3){
                    $params['price_one'] = 5;
                    $params['price_two'] = 10;
                }elseif ($budget == 4){
                    $params['price_one'] = 10;
                    $params['price_two'] = 50;
                }elseif ($budget == 5){
                    $params['price_one'] = 50;
                    $params['price_two'] = 100;
                }elseif ($budget == 6){
                    $params['price_one'] = 100;
                }

                $lists = Categorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
                $fields = ['id','title','price','urgent','number','end_at','created_at','content','bid'];
                //二级分类
                if(empty($params['cid'])){
                    $lists['children'] = Categorys::where('pid','<>','0')->get(['id','name','pid'])->toArray();
                }else{
                    $lists['children'] = Categorys::getcates(['pid'=>$params['cid']],['id','name','pid'])->toArray();
                }
                $lists['demand'] = Demands::allLists($params, $fields, $page, 5, $sort, $orderby);
                foreach ($lists['demand'] as $key=>$val){
                    $lists['demand'][$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['created_at'])));
                    $lists['demand'][$key]['end_at'] = trim(@date('Y-m-d', strtotime($val['end_at'])));
                    $lists['demand'][$key]['price'] = floatval($val['price']);
                }
                $lists['area'] = Areas::get(['id','name','pid']);//服务区域
            }elseif ($key == 5){
                $params['keyword'] = $keyword;
                if ($sid == 1){
                    $sort = 'view';
                }elseif ($sid == 2){
                    $sort = 'collect';
                }else{
                    $sort = 'created_at';
                }
                $fields = ['id','thumb','title','content','view','collect','created_at'];
                $lists = Articles::allLists($params,$fields,$page,5,$sort,$orderby);
                foreach ($lists as $key=>$val){
                    $lists[$key]['content'] = str_limit(strip_tags($val['content']) , 170 , '...' );//str_limit 字符截取 strip_tags 去除HTML标签
                    $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists[$key]['collect'] = strlen($val['collect'])>=4 ? '999+' : $val['collect'];
                }
            }elseif ($key == 6){
                $params['keyword'] = $keyword;
                if ($sid == 1){
                    $sort = 'download';
                }elseif ($sid == 2){
                    $sort = 'view';
                }else{
                    $sort = 'created_at';
                }
                $lists = WordCategorys::getcates(['pid'=>0],['id','name','pid']);
                $fields = ['id','thumb','title','summary','view','download','format','cate_id','cate_pid'];
                if(empty($cid)){
                    $lists['children'] = WordCategorys::where('pid','<>','0')->where('status','<>',-1)->get(['id','name','pid']);
                }else{
                    $lists['children'] = WordCategorys::getcates(['pid'=>$params['cid']],['id','name','pid']);
                }
                $lists['word'] = Words::allLists($params, $fields, $page, 5, $sort, $orderby);
                foreach ($lists['word'] as $key=>$val){
                    $lists['word'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists['word'][$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                }
            }

            //添加搜索记录START
            $hot_search = new HotSearchs();
            $info = HotSearchs::where("content", $keyword)->first();
            if ($info) {
                $hot_search = HotSearchs::find($info["id"]);
                $hot_search->count = $info["count"] + 1;
                $info->save();
            } else {
                $hot_search->content = $keyword;
                $hot_search->count = 1;
                $hot_search->type = $key;
            }
            $hot_search->save();
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


}